package com.xl.tools;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.compress.utils.Lists;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 小蓝的二维码加大，横向布局
 */
public class EnPingQrCode {


    public static void main(String[] args) throws IOException {
//        File dir = new File("D:/daerweima/东成镇高铁站充电站");
//        String[] array = dir.list();
//
//        for (String pno : array) {
//            if(!pno.contains("_")){
//                continue;
//            }
//            String[] tArray = pno.split("_");
//            write(tArray[0], tArray[1].split("[.]")[0]);
//        }
//        List<String> piles = Lists.newArrayList();
//        for(long i =10012401319L; i <=  10012401333L  ; i++){
//            write(i+"","01");
//        }
//        write("20012400245","01");
//        write("20012400246","01");

    }

    public static void write(String code, String gun) throws IOException {
        FileInputStream logoFile = new FileInputStream(new File("D:/qrtest/295164745776650.png"));
        String dir = "D:/qrtest/全达/半岛一号快充站/" + code;
        File codeFile = new File(dir.concat("_").concat(gun).concat(".png"));
        codeFile.getParentFile().mkdirs();
        String qrUrl = "https://wx.chargeland.cn/qcode?code=" + code;
        String pileNoText = code;
        String gunNoText = gun;
        String title = "【扫一扫】开锁充电";
        drawLogoQRCodeSizeForTemplate(logoFile, codeFile, qrUrl, pileNoText, gunNoText, title);
    }


    public static BufferedImage drawLogoQRCodeSizeForTemplate(InputStream logo, File codeFile, String qrUrl, String pileNoText, String gunNoText, String title) throws IOException {
        int w = 600;
        int h = 350;
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
            private static final long serialVersionUID = 1L;

            {
                put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
                put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
                put(EncodeHintType.MARGIN, 0);
            }
        };

        Graphics2D g2d = image.createGraphics();
        Stroke defaultStroke = g2d.getStroke();
        Color defaultColor = g2d.getColor();

        g2d.setPaint(Color.white);

        g2d.fillRect(0, 0, w, h);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        int startX = 350;
        //算出右边的矩形
        Rectangle2D.Double rect = new Rectangle2D.Double();
        rect.x = startX;
        rect.y = 0;
        rect.width = 250;
        rect.height = h;

        g2d.setPaint(new Color(45, 140, 240));
        g2d.fill(rect);
        //画一个二维码框
        Stroke stroke = new BasicStroke(2);
        g2d.setPaint(Color.black);
        g2d.setStroke(stroke);
        rect = new Rectangle2D.Double();
        rect.x = 0;
        rect.y = 0;
        rect.width = 350;
        rect.height = h - 2;
        g2d.draw(rect);
        // 画左边二维码
        int padding = 10;
        int qrW = 350 - (padding << 1);

        Image qrImage = drawLogoQRCodeNoText(logo, qrUrl);
        g2d.drawImage(qrImage, padding, padding, qrW, qrW, null);
        //右边画支付宝 微信
        //
        try {
            Image wxPayImage = ImageIO.read(NanXingQrCodeUtils.class.getResourceAsStream("/qricon/wxtalk.png"));
            g2d.setPaint(Color.white);
            RoundRectangle2D roundRectangle2D = new RoundRectangle2D.Double(370, 30, 48, 48, 20, 20);
            g2d.fill(roundRectangle2D);
            g2d.drawImage(wxPayImage, 370, 30, 48, 48, null);
            //
            Image aliPayImage = ImageIO.read(NanXingQrCodeUtils.class.getResourceAsStream("/qricon/alipay.png"));
            g2d.setPaint(Color.white);
            roundRectangle2D = new RoundRectangle2D.Double(w - 20 - 48, 30, 48, 48, 24, 24);
            g2d.fill(roundRectangle2D);
            g2d.drawImage(aliPayImage, w - 20 - 48, 30, 48, 48, null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //
        String text = "[扫一扫]启动充电";
        if (title != null && !title.trim().equals("")) {
            text = title;
        }
        g2d.setPaint(Color.white);
        g2d.setStroke(defaultStroke);
        g2d.setFont(new Font("楷体", Font.BOLD, 23));
        int textWidth = g2d.getFontMetrics().stringWidth(text);
        int x = (w - 350 - textWidth) >> 1;
        int y = 10 + g2d.getFontMetrics().getHeight() + 48 + 30;
        g2d.drawString(text, x + 350, y);


        String pileNo = "桩编号：" + pileNoText;
        String gunNo = "枪  号：" + gunNoText + " #";

        int tx;
        int ty = y + 10 + g2d.getFontMetrics().getHeight();
        g2d.setPaint(Color.white);
        Font font = new Font("楷体", Font.BOLD, 20);
        g2d.setFont(font);

        tx = 370;
        g2d.drawString(pileNo, tx, ty);
        ty += 30;
        g2d.drawString(gunNo, tx, ty);

        //
        String company = "小蓝快充新能源科技（深圳）有限公司";
        font = new Font("楷体", Font.BOLD, 13);
        g2d.setFont(font);
        y = (h - g2d.getFontMetrics().getHeight() - 10);
        g2d.drawString(company, tx - 15, y);
        // 说明
        y -= 10;
        String[] array = {"4.插好枪启动充电", "3.车辆进入充电车位", "2.点击“降锁”", "1.扫码进入小程序"};
        for (String note : array) {
            font = new Font("楷体", Font.BOLD, 13);
            g2d.setFont(font);
            y -= 20;
            g2d.drawString(note, tx, y);
        }

        g2d.dispose();
        image.flush();
        if (codeFile != null) {
            codeFile.getParentFile().mkdirs();
            codeFile.createNewFile();
            ImageIO.write(image, "png", codeFile);
            System.out.println(codeFile.getAbsolutePath());
        }
        return image;
    }


    public static BufferedImage drawLogoQRCodeNoText(InputStream logo, String qrUrl) {
        int w = 370;
        int h = 370;
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        int QRCOLOR = 0xFF000000; // 默认是黑色
        int BGWHITE = 0xFFFFFFFF; // 背景颜色
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
            private static final long serialVersionUID = 1L;

            {
                put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
                put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
                put(EncodeHintType.MARGIN, 0);
            }
        };
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
            BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, w, h, hints);

            // 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
            for (int x = 0; x < w; x++) {
                for (int y = 0; y < h; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }
            Font font = new Font("楷体", Font.BOLD, 20);
            int textHeight = font.getSize();
            // 新的图片，把带logo的二维码下面加上文字
            BufferedImage outImage = new BufferedImage(w + 10, h + 12, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D outg = outImage.createGraphics();
            //白色背景
            outg.setPaint(Color.white);
            outg.drawRect(0, 0, outImage.getWidth(), outImage.getHeight());
            outg.fillRect(0, 0, outImage.getWidth(), outImage.getHeight());
            // 画二维码到新的面板
            outg.drawImage(image, 5, 6, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            outg.setColor(Color.BLACK);
            outg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            outg.dispose();
            outImage.flush();
            image = outImage;
            if (logo != null) {
                // 构建绘图对象
                Graphics2D g = image.createGraphics();
                // 读取Logo图片
                BufferedImage logoImg = ImageIO.read(logo);
                // 开始绘制logo图片
                Rectangle rect = new Rectangle((outImage.getWidth() - logoImg.getWidth()) / 2 - 1, (h + 10 - logoImg.getHeight()) / 2 - 1, logoImg.getWidth() + 2, logoImg.getHeight() + 2);
                g.fillRoundRect(rect.x, rect.y, rect.width, rect.height, 2, 2);
                g.drawImage(logoImg, rect.x + 2, rect.y + 2, 64, 64, null);
                g.dispose();
                logoImg.flush();
            }
            image.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }


}
